package com.rmiad.controller;

import org.noear.snack.ONode;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Get;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.AppClassLoader;
import org.noear.solon.core.handle.Result;
import org.noear.solon.core.util.ResourceUtil;
import org.noear.solon.hotplug.PluginInfo;
import org.noear.solon.hotplug.PluginManager;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wyl
 * @date 2025年05月03日 上午10:02
 */
@Controller
public class SiteController {

    @Get
    @Mapping("/sys/site")
    public Result<ONode> site() throws Throwable {
        ONode siteNode = null;
        for (String uri : ResourceUtil.scanResources(AppClassLoader.global(), "classpath:static/pages/**/site.json")) {
            URL url = ResourceUtil.findResource(uri, false);
            if (url == null) {
                throw new IllegalArgumentException("Can't find resource: " + uri);
            }
            if (siteNode == null) {
                siteNode = ONode.load(ResourceUtil.getResourceAsString(url));
            } else {
                siteNode.get("pages").get(0).get("children").addAll(ONode.load(ResourceUtil.getResourceAsString(url)).get("pages").get(0).get("children"));
            }
        }
        List<PluginInfo> pluginInfoList = new ArrayList<>(PluginManager.getPlugins());
        for (int i = 0; i < pluginInfoList.size(); i++) {
            for (String uri : ResourceUtil.scanResources(pluginInfoList.get(i).getAddinPackage().getClassLoader(),
                    "classpath:static/pages/**/site.json")) {
                URL url = ResourceUtil.findResource(pluginInfoList.get(i).getAddinPackage().getClassLoader(),
                        uri, false);
                if (url == null) {
                    throw new IllegalArgumentException("Can't find resource: " + uri);
                }
                if (siteNode == null) {
                    siteNode = ONode.load(ResourceUtil.getResourceAsString(url));
                } else {
                    siteNode.get("pages").get(0).get("children").addAll(ONode.load(ResourceUtil.getResourceAsString(url)).get("pages").get(0).get("children"));
                }
            }
        }
        return Result.succeed(siteNode);
    }

}
